package client_gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

import utils.Constants;
import utils.ImageCreator;
import client.ClientApplication;
import client.ClientBindObject;
import client.ClientSocketConnection;
import client_gui_chat.ChatDialog;

/**
 * Klasa predstavlja dialog za izbor avatara.
 * Klikom na OK dugme ovog dialoga, serveru se salje komanda za promenu avatara.
 * 
 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
 */
public class AvatarDialog extends JDialog implements Constants {

	/**
	 * Parent - glavni prozor aplikacije
	 */
	private ClientWindow parent = null;
	private RegisterDialog parent_2 = null;
	private ChatDialog parent_3 = null;
	
	
	enum Parents { ClientWindow, RegisterDialog, ChatDialog };
	private Parents parentType = Parents.ClientWindow;
	
	
	private JPanel jContentPane = null;
	
	
	// kommponente dialoga
	private JScrollPane scrollPane = null;
	private JPanel avatarPanel = null;
	private JPanel buttonPanel = null;
	private JPanel avatarViewPanel = null;
	private JButton okButton = null;
	private JButton cancelButton = null;
	private JButton viewButton = null;
	
	
	/**
	 * String koji predstavlja ID avatara.
	 */
	private String newAvatarID = new String();
	
	
	
	/**
	 * Konstruktor.
	 * @param parent - parent window
	 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
	 */
	public AvatarDialog(ClientWindow parent) {
		super(parent, "Avatar Dialog", true);
		
		parentType = Parents.ClientWindow;
		
		this.parent = parent;
		
		// default avatar
		newAvatarID = DEFAULT_AVATAR;
		
		initialize();
	}
	
	
	/**
	 * Konstruktor.
	 * @param parent - parent ukoliko se otvara iz dijaloga za registraciju
	 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
	 */
	public AvatarDialog(RegisterDialog parent) {
		super(parent, "Avatar Dialog", true);
		
		parentType = Parents.RegisterDialog;
		
		this.parent_2 = parent;
		this.parent = parent_2.getRegisterOwner();
		
		// default avatar
		newAvatarID = DEFAULT_AVATAR;
		
		initialize();
	}
	
	
	/**
	 * Konstruktor.
	 * @param parent - parent ukoliko se otvara iz dijaloga za chat
	 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
	 */
	public AvatarDialog(ChatDialog parent) {
		super(parent, "Avatar Dialog", true);
		
		parentType = Parents.ChatDialog;
		
		this.parent_3 = parent;
		this.parent = parent_3.getChatOwner();
		
		// default avatar
		newAvatarID = DEFAULT_AVATAR;
		
		initialize();
	}
	
	
	/**
	 * Metod vrsi inicijalizaciju dialoga.
	 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
	 */
	private void initialize() {
		this.setSize(340, 400);
		if ( parentType == Parents.ClientWindow || parentType == Parents.RegisterDialog )
			this.setLocation(parent.getX() + parent.getWidth() / 2 - this.getWidth() / 2, parent.getY() + parent.getHeight() / 2 - this.getHeight() / 2);
		else
			this.setLocation(parent_3.getX() + parent_3.getWidth() / 2 - this.getWidth() / 2, parent_3.getY() + parent_3.getHeight() / 2 - this.getHeight() / 2);
		this.setResizable(false);
		this.setContentPane(getJContentPane());
		
		this.setIconImage(parent.getIconImage());
	}
	
	
	
	// Metode koje inicijalizuju komponente dialoga.
	
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			
			jContentPane.setLayout(new BorderLayout());
			
			jContentPane.add(getAvatarViewPanel(), BorderLayout.NORTH);
			jContentPane.add(getScrollPane(), BorderLayout.CENTER);
			jContentPane.add(getButtonPanel(), BorderLayout.SOUTH);
		}
		
		return jContentPane;
	}
	
	
	
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			
			scrollPane.setViewportView(getAvatarPanel());
		}
		
		return scrollPane;
	}
	
	
	private JPanel getAvatarPanel() {
		if (avatarPanel == null) {
			avatarPanel = new JPanel();
			avatarPanel.setPreferredSize(new Dimension(315,615));
			FlowLayout apFlow = new FlowLayout(FlowLayout.CENTER);
			apFlow.setHgap(10);
			apFlow.setVgap(10);
			avatarPanel.setLayout(apFlow);
			
			for (int i = 0; i < 50; i++) {
				avatarPanel.add(new AvatarButton(i+1));
			}
		}
		
		return avatarPanel;
	}
	
	
	private JPanel getButtonPanel() {
		if (buttonPanel == null) {
			buttonPanel = new JPanel();
			FlowLayout bpFlow = new FlowLayout(FlowLayout.CENTER);
			bpFlow.setHgap(20);
			buttonPanel.setLayout(bpFlow);
			
			buttonPanel.add(getOKButton());
			buttonPanel.add(getCancelButton());
		}
		
		return buttonPanel;
	}
	
	
	
	private JButton getOKButton() {
		if (okButton == null) {
			okButton = new JButton("OK");
			okButton.setPreferredSize(new Dimension(80,24));
			okButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					if (parent.getApplicaton().getState() == LOGGED_STATE) {
						changeAvatar();
						
						if (parent_3 != null) {
							parent_3.setAvatar(newAvatarID);
						}
						
						Enumeration<String> keys = ClientApplication.clientBinding.keys();
						while ( keys.hasMoreElements() ) {
							String key = keys.nextElement();
							ClientBindObject cbo = ClientApplication.clientBinding.get(key);
							if ( cbo.isDialogOpen() ) {
								cbo.getDialog().setAvatar(newAvatarID);
							}
						}
					}
					else {
						if ( parent_2 != null ) {
							parent_2.setAvatar(newAvatarID);						
						}
					}
					
					AvatarDialog.this.dispose();
				}
			});
		}
		
		return okButton;
	}
	
	
	private void changeAvatar() {
		ClientSocketConnection connection = parent.getApplicaton().retrieveSocketConnection();
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("CHAVATAR ");
		buffer.append(parent.getApplicaton().getClientUser().getUsername());
		buffer.append(" ");
		buffer.append(newAvatarID);
		
		String completedAvatarInfo = buffer.toString();
		
		connection.setMessage(CHAVATAR_CMD, completedAvatarInfo);
		
		String response;
		
		response = connection.buffers[CHAVATAR_CMD].read();
		
		if ( response.startsWith("100") ) {
			
			parent.getApplicaton().getClientUser().setAvatar(newAvatarID);
			
			parent.setAvatar(newAvatarID);
		}
		
	}
	
	
	
	
	private JButton getCancelButton() {
		if (cancelButton == null) {
			cancelButton = new JButton("Cancel");
			cancelButton.setPreferredSize(new Dimension(80,24));
			
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					newAvatarID = DEFAULT_AVATAR;
					AvatarDialog.this.dispose();
				}
			});
		}
		
		return cancelButton;
	}
	
	
	
	private JPanel getAvatarViewPanel() {
		if (avatarViewPanel == null) {
			avatarViewPanel = new JPanel();
			
			viewButton = new JButton();
			viewButton.setPreferredSize(new Dimension(50,50));
						
			viewButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
			
			viewButton.setIcon(ImageCreator.createImageIcon(AvatarDialog.class, DEFAULT_AVATAR));
			
			TitledBorder titledBorder = BorderFactory.createTitledBorder(BorderFactory.
					createEtchedBorder(EtchedBorder.RAISED),
					"Avatar", javax.swing.border.TitledBorder.CENTER,
					javax.swing.border.TitledBorder.DEFAULT_POSITION,
					null, null);
			
			avatarViewPanel.setBorder(titledBorder);
			
			avatarViewPanel.add(viewButton);
		}
		
		return avatarViewPanel; 
	}
	

	

	
	/**
	 * Privatna klasa koja predstavlja svaki avatar u ovom dialogu.
	 * Klasa ima atribu avatarPath, na osnovu koga se ucitavaju ikonice avatara.
	 * Klasa nasledjuje JButton klasu, sto omogucava prikaz avatara kao dugmeta.
	 * Klasa implementira ActionListener interface, sto omogucava osluskivanje
	 * dogadjaja klikom na avatar dugme.
	 * Akcije dugmeta:
	 * 		- setovanje ikonice na view avataru
	 * 		- setovanje novog avatara u newAvatarID atributu
	 * 
	 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
	 */
	private class AvatarButton extends JButton implements ActionListener {
		
		/**
		 * Putanja do avatara.
		 */
		private String avatarPath = "/avatars/avatar";
		
		
		/**
		 * Konstruktor.
		 * @param avatarNo - broj dobijen iz for petlje
		 * @see AvatarDialog#getAvatarPanel()
		 * @author UrosKrkic & Radivoje Popovic & Martin Jondzic
		 */
		public AvatarButton(int avatarNo) {
			super();
			
			if (avatarNo < 10) {
				avatarPath = avatarPath + "0" + avatarNo + ".png";
			}
			else {
				avatarPath = avatarPath + avatarNo + ".png";
			}
			
			this.setPreferredSize(new Dimension(50,50));
			this.setIcon(ImageCreator.createImageIcon(AvatarDialog.class, avatarPath));
			this.addActionListener(this);
		}
		
		
		/**
		 * Obradjivanje akcije klika na dugme avatara.
		 */
		public void actionPerformed(ActionEvent e) {
			viewButton.setIcon(this.getIcon());
			
			int ind = avatarPath.lastIndexOf("/");
			ind++;
			String avatarID = avatarPath.substring(ind);
			
			newAvatarID = avatarID.substring(0, avatarID.length()-4);
		}
	}
	

}
